package redis

import (
	"cart_srv/pb/cart"
	"context"
	"fmt"
	"strconv"
)

func AddCart(userId int64, goodsId int64, cart map[string]interface{}) error {
	key := fmt.Sprintf("cart:user_id_%d:goods_id_%d", userId, goodsId)

	return Rdb.HMSet(context.Background(), key, cart).Err()
}
func GetExist(userId int64, goods int64) bool {
	key := fmt.Sprintf("cart:user_id_%d:goods_id_%d", userId, goods)
	return Rdb.Exists(context.Background(), key).Val() == 1
}

func UpdateCart(userId int64, goodsId int64, num int64) error {
	key := fmt.Sprintf("cart:user_id_%d:goods_id_%d", userId, goodsId)
	return Rdb.HSet(context.Background(), key, "num", num).Err()
}
func CartList(userId int64) (cartList []*cart.CartList) {
	key := fmt.Sprintf("cart:user_id_%d:*", userId)
	keys := Rdb.Keys(context.Background(), key).Val()

	for _, v := range keys {
		goods := Rdb.HGetAll(context.Background(), v).Val()
		userid, _ := strconv.Atoi(goods["user_id"])
		goodsId, _ := strconv.Atoi(goods["goods_id"])
		num, _ := strconv.Atoi(goods["num"])
		goodsPrice, _ := strconv.ParseFloat(goods["goods_price"], 64)

		list := &cart.CartList{
			UserId:     int64(userid),
			GoodsId:    int64(goodsId),
			Num:        int64(num),
			GoodsTitle: goods["goods_title"],
			GoodsCover: goods["goods_cover"],
			GoodsPrice: float32(goodsPrice),
		}
		cartList = append(cartList, list)
	}
	return
}
func DelCart(userId int64) error {
	key := fmt.Sprintf("cart:user_id_%d:*", userId)
	return Rdb.Del(context.Background(), key).Err()

}
func ClearCart(userId int64) {
	key := fmt.Sprintf("cart:user_id_%d:*", userId)
	keys := Rdb.Keys(context.Background(), key).Val()
	for _, v := range keys {
		Rdb.Del(context.Background(), v)
	}
}
